package com.sgj.service.impl;

import com.sgj.dao.BlogRepository;
import com.sgj.exception.NotFoundExcepiton;
import com.sgj.pojo.Blog;
import com.sgj.pojo.Tag;
import com.sgj.pojo.Type;
import com.sgj.service.BlogService;
import com.sgj.utils.MarkdownUtils;
import com.sgj.utils.MyBeanUtils;
import com.sgj.vo.BlogRes;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;
import javax.transaction.Transactional;
import java.util.*;

/**
 * @author 沈国纪
 * @date 2021/3/31 14:10
 */
@Service
public class BlogServiceImpl implements BlogService {

	@Autowired
	private BlogRepository blogRepository;

	/**
	 * 根据 id 查询博客
	 * @param id
	 * @return
	 */
	@Override
	public Blog getBlog(Long id) {
		return blogRepository.getOne(id);
	}

	/**
	 * 获取博客内容并转换成 Markdown 可识别的 HTML 内容
	 * @param id
	 * @return
	 */
	@Transactional
	@Override
	public Blog getAndConvert(Long id) {
		Blog blog = blogRepository.getOne(id);
		if (Objects.isNull(blog)) {
			throw new NotFoundExcepiton("该博客不存在");
		}
		// 将博客内容转换为 Markdown 可识别的 HTML 内容
		Blog b = new Blog();
		BeanUtils.copyProperties(blog, b);
		b.setContent(MarkdownUtils.markdownToHtmlExtensions(b.getContent()));

		// 每次打开博客浏览量+1
		blogRepository.updateView(id);
		return b;
	}

	/**
	 * 分页查询
	 * @param pageable
	 * @param blogRes
	 * @return
	 */
	@Override
	public Page<Blog> listBlog(Pageable pageable, BlogRes blogRes) {
		// 动态查询
		return blogRepository.findAll(new Specification<Blog>() {
			@Override
			public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
				List<Predicate> predicates = new ArrayList<>();
				if (Objects.nonNull(blogRes)) {
					// 动态添加标题条件
					if (StringUtils.isNotBlank(blogRes.getTitle())) {
						predicates.add(criteriaBuilder.like(root.<String>get("title"), "%" + blogRes.getTitle() + "%"));
					}
					// 动态添加类型条件
					if (Objects.nonNull(blogRes.getTypeId())) {
						predicates.add(criteriaBuilder.equal(root.<Type>get("type").get("id"), blogRes.getTypeId()));
					}
					// 动态添加是否推荐条件
					if (blogRes.isRecommend()) {
						predicates.add(criteriaBuilder.equal(root.<Boolean>get("recommend"), blogRes.isRecommend()));
					}
					criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()]));
				}
				return null;
			}
		}, pageable);
	}

	/**
	 * 页面初始化
	 * @param pageable
	 * @return
	 */
	@Override
	public Page<Blog> listBlog(Pageable pageable) {
		return blogRepository.findAll(pageable);
	}

	/**
	 * 根据标签查询博客
	 * @param tagId
	 * @param pageable
	 * @return
	 */
	@Override
	public Page<Blog> listBlog(Long tagId, Pageable pageable) {
		return blogRepository.findAll(new Specification<Blog>() {
			@Override
			public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
				Join join = root.join("tags");
				return criteriaBuilder.equal(join.get("id"), tagId);
			}
		}, pageable);
	}

	/**
	 * 查询功能
	 * @param query
	 * @param pageable
	 * @return
	 */
	@Override
	public Page<Blog> listBlog(String query, Pageable pageable) {
		// 增加字符串模糊查询条件
		query = "%" + query + "%";
		return blogRepository.findByQuery(query, pageable);
	}

	/**
	 * 根据分页条件查询博客
	 * @param size
	 * @return
	 */
	@Override
	public List<Blog> listRecommendBlogTop(Integer size) {
		Sort sort = Sort.by(Sort.Direction.DESC, "updateTime");
		Pageable pageable = PageRequest.of(0, size, sort);
		return blogRepository.findTop(pageable);
	}

	/**
	 * 查询对应年份博客
	 * @return
	 */
	@Override
	public Map<String, List<Blog>> archiveBlog() {
		List<String> years = blogRepository.findGroupYear();
		Map<String, List<Blog>> map = new HashMap<>();
		for (String year : years) {
			map.put(year, blogRepository.findByYear(year));
		}
		return map;
	}

	/**
	 * 查询总博客数量
	 * @return
	 */
	@Override
	public Long countBlog() {
		return blogRepository.count();
	}

	/**
	 * 新增博客
	 * @param blog
	 * @return
	 */
	@Transactional
	@Override
	public Blog saveBlog(Blog blog) {
		blog.setCreateTime(new Date());
		blog.setUpdateTime(new Date());
		blog.setViews(0);
		return blogRepository.save(blog);
	}

	/**
	 * 修改博客
	 * @param blog
	 * @return
	 */
	@Transactional
	@Override
	public Blog updateBlog(Blog blog) {
		Blog b = blogRepository.getOne(blog.getId());
		if (b == null) {
			throw new NotFoundExcepiton("不存在该博客");
		}
		BeanUtils.copyProperties(blog, b, MyBeanUtils.getNullPropertyNames(blog));
		b.setUpdateTime(new Date());
		return blogRepository.save(b);
	}

	/**
	 * 删除博客
	 * @param id
	 */
	@Transactional
	@Override
	public void deleteBlog(Long id) {
		blogRepository.deleteById(id);
	}
}
